<template>
  <div id="personal">
    <top-bar :title="title"></top-bar>
    <div class="personal_list">
      <md-field>
        <md-field-item name title="头像" align="right">
          <md-image-reader name="reader0" @complete="onReaderComplete" is-multiple :mime="['jpg','png','jpeg']"></md-image-reader>
          <img :src="userPoto" class="personalpoto" v-if="userPoto" />
          <img src="@/assets/imgs/dt_cktx_big.png" class="personalpoto" v-else />
        </md-field-item>
        <md-field-item name title="呢称" arrow="arrow-right" @click="modifyName" :value="userName" align="right"></md-field-item>
        <md-field-item name title="性别" arrow="arrow-right" @click="modifySex" :value="userSex" align="right"></md-field-item>
        <md-field-item name title="手机号" :value="userPhone" align="right"></md-field-item>
      </md-field>
      <md-selector v-model="isSelectorShow" :data="sexData[0]" :default-index="1" title="选择性别" okText="确认" cancelText="取消" @confirm="onSelectorConfirm($event)"></md-selector>
    </div>
    <div class="personalCode">
      <md-field>
        <md-field-item name title="我的二维码" arrow="arrow-right" align="right" @click="PersonalCode">
          <md-icon name="qrcode"></md-icon>
        </md-field-item>
      </md-field>
    </div>
  </div>
</template>
<script>
import '@/assets/svgs/qrcode.svg';
import { Icon, Field, FieldItem, Toast, Dialog, ImageReader, Selector } from 'mand-mobile';
import TopBar from '@/components/TopBar';
import Loading from '@/components/loading';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import http from '@/common/http';
import OSS from 'ali-oss';
import Config from '@/common/config';
let client = new OSS({
  region: 'oss-cn-qingdao',
  accessKeyId: 'LTAI0oUoBK7GwQn4',
  accessKeySecret: 'gHqAlhq2pX57Jz8XCO0zMLsKlZoAlX',
  bucket: 'pakj'
});
export default {
  components: {
    [Icon.name]: Icon,
    [TopBar.name]: TopBar,
    [Field.name]: Field,
    [Toast.name]: Toast,
    [FieldItem.name]: FieldItem,
    [ImageReader.name]: ImageReader,
    [Selector.name]: Selector
  },
  data() {
    return {
      title: '个人信息',
      userName: '',
      userPhone: '',
      userPoto: '',
      userSex: '',
      isSelectorShow: false,
      is_identity: '',
      photoUrl: '',
      sexData: [
        [
          {
            text: '男'
          },
          {
            text: '女'
          }
        ]
      ]
    };
  },
  created() {
    let str = localStorage.getItem('USER_INFO');
    let userobj = JSON.parse(str);
    let params = {
      tk: userobj.token
    };
    Loading.show();
    http.post('pakj/passenger/getUserInfo', params).then(res => {
      Loading.hide();
      console.log(res.data);
      if (res.data.code === '000000') {
        this.userName = res.data.data.nick_name;
        localStorage.setItem('nick_name', res.data.data.nick_name);
        this.userPhone = decryptByDESModeEBC(res.data.data.user_phone);
        // this.userPoto = res.data.data.user_headpath;
        if (res.data.data.user_headpath) {
          // this.userPoto = Config.ossImgUrl + res.data.data.user_headpath.replace(/^http:\/\//, 'https://');
          this.userPoto = Config.ossImgUrl + res.data.data.user_headpath;
        }
        if (!res.data.data.user_sex) {
          this.userSex = '';
        } else {
          this.userSex = res.data.data.user_sex;
        }
        this.is_identity = res.data.data.is_identity;
      } else {
        Dialog.alert({
          title: '提示',
          content: res.data.msg,
          confirmText: '确定'
        });
      }
    });
  },
  methods: {
    // 设置昵称
    modifyName() {
      this.$router.push({
        name: 'SetpPersonalName'
      });
    },
    // 我的二维码
    PersonalCode() {
      this.$router.push({
        name: 'PersonalCode'
      });
    },
    // 选择性别
    modifySex() {
      if (this.is_identity !== '1') {
        this.isSelectorShow = true;
      }
    },
    // 上传头像
    onReaderComplete(name, file) {
      Loading.show();
      if (file.file.type === 'image/jpeg' || file.file.type === 'image/png') {
        var date = new Date();
        var time = '' + date.getFullYear() + (date.getMonth() + 1) + date.getDate();
        var storeAs = 'headimg/' + time + '-' + date.getTime() + '.' + file.file.name;
        // blob转arrayBuffer
        var reader = new FileReader();
        reader.readAsArrayBuffer(this.dataURLtoFile(file.dataUrl));
        reader.onload = event => {
          var buffer = new OSS.Buffer(event.target.result);
          client
            .put(storeAs, buffer, {})
            .then(results => {
              this.photoUrl = 'https://img.padj.group/' + results.name;
              // this.photoUrl = Config.ossImgUrl + results.name
              this.userPoto = file.dataUrl;
              this.PhotoBtn();
            })
            .catch(err => {
              Loading.hide();
              console.log(err);
            });
        };
      } else {
        Loading.hide();
        Dialog.alert({
          title: '提示',
          content: '图片格式错误',
          confirmText: '确定'
        });
      }
    },
    dataURLtoFile(dataurl) {
      const arr = dataurl.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    PhotoBtn() {
      let str = localStorage.getItem('USER_INFO');
      let userobj = JSON.parse(str);
      var data = {
        tk: userobj.token,
        user_headpath: this.photoUrl
      };
      http.post('/pakj/passenger/updateUserInfo', data).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          var userHeadpathUrl = '';
          if (res.data.data.user_headpath) {
            userHeadpathUrl = Config.ossImgUrl + res.data.data.user_headpath;
          }
          Dialog.alert({
            title: '提示',
            content: '头像修改成功',
            confirmText: '确定',
            onConfirm: () => {
              localStorage.setItem('user_headpath', userHeadpathUrl);
              this.$router.push({
                name: 'PersonalIndex'
              });
            }
          });
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
        }
      });
    },
    onSelectorConfirm(obj) {
      this.userSex = obj.text;
      let str = localStorage.getItem('USER_INFO');
      let userobj = JSON.parse(str);
      var data = {
        tk: userobj.token,
        user_sex: this.userSex
      };
      Loading.show();
      http.post('/pakj/passenger/updateUserInfo', data).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          Dialog.alert({
            title: '提示',
            content: '性别修改成功',
            confirmText: '确定',
            onConfirm: () => {
              this.$router.push({
                name: 'PersonalIndex'
              });
            }
          });
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
        }
      });
    }
  }
};
</script>
<style lang="stylus" scoped>
p {
  display: block;
  margin-block-start: 0px;
  margin-block-end: 0px;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
}

#personal {
  height: 100vh;
  background-color: color-primary-background;
}

.personal_list {
  margin-top: 20px;
}

.personalCode {
  margin-top: 20px;
}

.personalpoto {
  width: 56px;
  height: 56px;
  border-radius: 50%;
}
</style>
